package com.didi.gulimall.auth.controller;

import com.didi.gulimall.auth.service.OAuth2Service;
import com.didi.gulimall.common.constant.AuthServerConstant;
import com.didi.gulimall.common.to.MemberResponseVo;
import com.didi.gulimall.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @author 10626
 */
@Controller
@Slf4j
@Api("权限登录")
public class OAuth2Controller {
    @Autowired
    private OAuth2Service oAuth2Service;

    @Value("${gulimall.home}")
    private String homeHtml;

    @Value("${gulimall.login}")
    private String loginHtml;

    @ApiOperation("微博code响应")
    @GetMapping("oauth2/weibo/success")
    public String oauthWeiboSuccess(
            @ApiParam(name = "code", value = "code响应值（换取Access Token）", required = true)
            @RequestParam("code") String code,
            RedirectAttributes redirectAttributes,
            HttpSession session) {
        try {
            return oAuth2Service.oauthWeiboSuccess(code,session,redirectAttributes);
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:"+loginHtml;
        }
    }
    @ApiOperation("获取页面登录")
    @GetMapping("/login.html")
    public String loginHtml(
            HttpSession session) {
        MemberResponseVo attribute = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute != null) {
            return "redirect:" + homeHtml;
        }
        return "login";
    }
}
